#include <iostream>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <strings.h>
#include <unistd.h>
#include "tcpserver.h"
TcpServer::TcpServer(): port_(7777), ip_("0"), backlog_(10) { }
TcpServer::TcpServer(const int port, const char* ip, const int backlog):
    port_(port), ip_(ip), backlog_(backlog)
{ }
int TcpServer::TcpInit()
{
    int                sockfd, ret;
    struct sockaddr_in addr;
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(-1 == sockfd) {
        perror("create socket:");
        return -1;
    }
    printf("socket create success\n");
    //设置地址重用
    int opt = 1;
    if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) {
        perror("setsockopt error");
    }

    addr.sin_family      = AF_INET;
    addr.sin_port        = htons(port_);
    addr.sin_addr.s_addr = inet_addr(ip_);
    ret                  = bind(sockfd, (struct sockaddr*)&addr, sizeof(addr));
    if(-1 == ret) {
        perror("bind:");
        return -1;
    }
    printf("socket bind success\n");

    ret = listen(sockfd, backlog_);
    if(-1 == ret) {
        perror("listen");
        return -1;
    }
    printf("listen success\n");
    return sockfd;
}
int TcpServer::TcpAceept(int listenfd)
{
    int                acceptfd;
    struct sockaddr_in clientaddr;
    socklen_t          clientlen = sizeof(clientaddr);
    acceptfd = accept(listenfd, (struct sockaddr*)&clientaddr, &clientlen);
    // ret = accept(listenfd,NULL,NULL);
    if(-1 == acceptfd) { perror("accept:"); }
    printf("accept success,ip is:%s,port is %d\n",
        inet_ntoa(clientaddr.sin_addr), clientaddr.sin_port);
    return acceptfd;
}